<script lang="ts" setup>
import { onMounted, reactive, ref, unref, watch } from 'vue';
// import { Select } from 'ant-design-vue';
import { getEnergyStationMarker } from '#/api';
import { boilerDatas,extractContent } from './home.data.ts';
import markerRed from '#/assets/poi-marker-red.png';
import { useScript } from '#/hooks/useScript';
import { preferences } from '@vben/preferences';
const theme = preferences.theme.mode;
const props = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: 'calc(100vh - 90px)',
  },
});

const wrapRef = ref<HTMLDivElement | null>(null);
const TMap = ref();
const state = reactive({
  gMap: null,
  marker: null,
  infoWindow: null, // 信息窗体对象
  cityActive: '110107', // 默认选择区域
  cityOptions: [],
  boilerRoomDatas: [], // 锅炉房
  Polygons: null,
});

// const key =2LVBZ-CIA63-YFS3E-OULYH-WCAKO-3BF7D
const TECENT_MAP_URL =
  'https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&libraries=service';
const { load } = useScript({ src: TECENT_MAP_URL });

watch(
  () => preferences.theme.mode,
  (value) => {
    if (state.gMap) {
      state.gMap.setMapStyleId(value==='dark'? 'style1':'style')
   }
  },
  {
    immediate: true,
  },
);

const initMap = async () => {
  await load();
  setTimeout(() => {
    const wrapEl = unref(wrapRef);
    if (!wrapEl) return;
    TMap.value = (window as any).TMap;

    const center = new TMap.value.LatLng(39.908_802, 116.397_502); // 设置中心点坐标
    state.gMap = new TMap.value.Map(wrapEl, {
      zoom: 12, // 设置地图缩放级别
      mapStyleId:theme=='dark'? 'style1':'',
      center,
    });
    initData()
  }, 100);
};

onMounted(async() => {
  const res= await getEnergyStation()
  initMap();
});

// 添加marker事件
const addMarker = (TMap: any) => {
  let boilerData = state.boilerRoomDatas;
  let markerArr = [];
  if (boilerData.length === 0) {
    markerArr = [];
    return;
  }
  boilerData.map((item, index) => {
    const { name, longitude, latitude} = item;
    markerArr.push({
      id: `marker${index}`,
      position: new TMap.LatLng(Number(latitude), Number(longitude)),
      properties: {
        title: name || '',
      },
      list: item,
    });
  });
  state.marker = new TMap.MultiMarker({
    id: `marker-layer`,
    map: state.gMap,
    styles: {
      marker: new TMap.MarkerStyle({
        width: 20,
        height: 28,
        anchor: { x: 16, y: 32 },
        src: markerRed,
      }),
    },
    geometries: markerArr,
  });

  initInfoWindow(); // 初始化信息窗体
  state.infoWindow.close();
  // 监听回调函数（非匿名函数）
  const eventClick = (evt) => {
    state.infoWindow.open();
    state.infoWindow.setPosition(evt.geometry.position);
    const content = formatContent(evt.geometry.list);
    state.infoWindow.setContent(content);
  };
  // state.marker.addListener('mouseover', eventClick);
  // state.marker.addListener('mouseout', ()=> {
  //   state.infoWindow.close(); // 鼠标移出时关闭信息窗体，可选操作
  // });
  state.marker.on('click', eventClick);
};

/** 移除marker */
const removeMarker = () => {
  if (state.marker) {
    state.marker.setMap(null);
    state.marker = null;
  }
};

/** 初始化infoWindow*/
const initInfoWindow = () => {
  const content = `<div class="custom-info-card">
          <div class="info-card-title">
           <span>北京京能热力股份有限公司</span>
          </div>
          <div class="info-card-subTitle">(雍景四季东区锅炉房)</div>
          <div class="info-card-body">
            <p>热力生产和供应 简化管理</p>
            <p>蒸吨数：9.9</p>
          </div>
        </div>`;
  state.infoWindow = new TMap.value.InfoWindow({
    map: state.gMap,
    // enableCustom:true,
    position: new TMap.value.LatLng(39.984_104, 116.307_503), // 设置信息框位置
    content: content, // 设置信息框内容
    offset: { x: -3, y: -50 },
  });
};

/** 格式化窗体内容 */
const formatContent = (list: any) => {
  const { outside, inside } = extractContent(list.shortName);

  const content = `<div class="custom-info-card">
          <div class="info-card-title">
           <span>${outside}</span>
          </div>
          <div class="info-card-subTitle">${inside}</div>
          <div class="info-card-body">
            <div><span>${list.industryType}</span> <span style="margin-left:5px;" v-if="list.managesType">${list.managesType}</span></div>
            <p>蒸吨数：${list.steamTonnage}</p>
          </div>
        </div>`;
  return content;
};

/** 行政区域高亮 */
const highlight = () => {
  const district = new TMap.value.service.District({
    // 新建一个行政区划类
    polygon: 2, // 返回行政区划边界的类型
  });
  // 关键字搜索行政区划，110000 = 北京行政区划代码 110102东城区
  const cityCode = Number(state.cityActive);
  district.search({ keyword: cityCode }).then((result) => {
    if (!result && !result.result) return;
    // 获取省市区列表及其边界信息
    const paths = result.result[0][0].polygon;
    const location = result.result[0][0].location;
    state.gMap.setCenter(location);
  

    state.Polygons = new TMap.value.MultiPolyline({
      map: state.gMap,
      styles: {
        polyline: new TMap.value.PolylineStyle({
          color: '#017cf7', // 线条填充色，
          width: 8,
          lineCap: 'round',
          enableBloom: true, // 是否启用泛光  注：为true才会有效果
        }),
      },
      geometries: [
        {
          paths,
        },
      ]
    })
    // state.Polygons = new TMap.value.MultiPolygon({
    //   map: state.gMap,
    //   styles: {
    //     polygon: new TMap.value.PolygonStyle({
    //       color: 'rgba(0,125,255,0.7)', // 面填充色
    //       showBorder: false, // 是否显示拔起面的边线
    //       borderColor: '#00FFFF', // 边线颜色
    //       borderWidth: 10,
    //     }),
    //   },
    //   geometries: [
    //     {
    //       paths,
    //     },
    //   ],
    // });
  });
};

/** 根据行政区查询能源站 */
const getEnergyStation = async() => {
  state.boilerRoomDatas = boilerDatas;
  // const res = await getEnergyStationMarker();
  
};

/**加载数据 */
const initData = () => {
  addMarker(TMap.value)
  
  highlight();
}

/** 切换城市区域 */
const handleCityChange = async(val: any) => {
  state.cityActive = val;
  if (state.Polygons) {
    state.Polygons.destroy();
  }
  highlight(Number(val));
  removeMarker();
  addMarker(TMap.value);
};
</script>

<template>
  <div class="home-container bg-card">
    <div ref="wrapRef" :style="{ height, width }"></div>
    <!-- <div class="search-card bg-card p-4">
      <label>选择区域：</label>
      <Select
        v-model:value="state.cityActive"
        style="width: 200px"
        :options="state.cityOptions"
        @change="handleCityChange"
      />
    </div> -->
  </div>
</template>

<style lang="less" scoped>
.home-container {
  position: relative;
}
.search-card {
  border-radius: 3px;
  position: absolute;
  left: 20px;
  top: 30px;
  z-index: 1000 !important;
}

</style>
<style>
.custom-info-card {
  padding:0 8px;
  /* border:1px solid #199bf1; */
  /* box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);  */
  text-align: center;
}
.info-card-title ,.info-card-subTitle {
    color:#666;
    font-weight: bold;
    font-size:15px;
}
.info-card-body {
  margin-top:6px;
  text-align: left;
  color:#666;
  font-size:13px;
}
.info-card-body p {
  line-height: 24px;
}
</style>
